'use strict';

/**
 * @ngdoc service
 * @name passwordAgentApp.alertService
 * @description
 * # alertService
 * Service in the passwordAgentApp.
 */
angular.module('passwordAgentApp')
  .service('alertService', function ($rootScope, $timeout) {
    // AngularJS will instantiate a singleton by calling "new" on this function
    var alertService = {};

    // 创建一个全局的 alert 数组
    $rootScope.alerts = [];

    alertService.add = function (type, msg) {
      $rootScope.alerts = [];
      $rootScope.alerts.push({
        'type': type, 'msg': msg, close: function () {
          return alertService.closeAlert(this);
        }
      });
      alertService.timeOutClose();
    };

    alertService.timeOutClose = function () {

      //$rootScope.alertFunctions.push(function () {
      //  $rootScope.alerts = [];
      //});

      $timeout.cancel(alertService.p);
      //
      //
      alertService.p = $timeout(function () {
        console.log("$timeout clean");
        $rootScope.alerts = []
        //alertService.closeAlertIdx(index);

        //$rootScope.alerts = [];
        //$rootScope.alertFunctions

        //if ($rootScope.alertFunctions.length > 0) {
        //  return $rootScope.alertFunctions[0];
        //}
      }, 5000);


    };

    alertService.closeAlert = function (alert) {
      console.log("closeAlert");
      alertService.closeAlertIdx($rootScope.alerts.indexOf(alert));
    };

    alertService.closeAlertIdx = function (index) {
      $rootScope.alerts.splice(index, 1);
    };
    return alertService;
  });
